package com.sukaiyi.giteeideaplugin.component;

import com.intellij.icons.AllIcons;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.AnimatedIcon;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

/**
 * @author sukaiyi
 * @date 2020/07/03
 */
public class LoadingContainer extends JLayeredPane {

    private JPanel loadingPanel = null;
    private AnimatedIcon processIcon = null;
    private Component contentPanel = null;

    private static final Icon[] LOADING_ICONS = new Icon[]{
            AllIcons.Process.Big.Step_1,
            AllIcons.Process.Big.Step_2,
            AllIcons.Process.Big.Step_3,
            AllIcons.Process.Big.Step_4,
            AllIcons.Process.Big.Step_5,
            AllIcons.Process.Big.Step_6,
            AllIcons.Process.Big.Step_7,
            AllIcons.Process.Big.Step_8,
    };
    private static final Icon PASSIVE_ICON = AllIcons.Process.Big.Step_passive;
    public static final int CYCLE_LENGTH = com.intellij.ui.AnimatedIcon.Default.DELAY * LOADING_ICONS.length;

    public LoadingContainer(Loadable loadable) {
        loadingPanel = new TranslucenceJPanel(0.05f);
        loadingPanel.setOpaque(false);
        loadingPanel.setBackground(JBColor.BLACK);
        loadingPanel.setLayout(new BorderLayout());
        processIcon = new AnimatedIcon("loading", LOADING_ICONS, PASSIVE_ICON, CYCLE_LENGTH);
        loadingPanel.add(processIcon);
        super.add(loadingPanel, POPUP_LAYER);

        contentPanel = loadable.getContent();
        super.add(contentPanel, DEFAULT_LAYER);

        super.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                super.componentResized(e);
                loadingPanel.setBounds(0, 0, LoadingContainer.this.getWidth(), LoadingContainer.this.getHeight());
                contentPanel.setBounds(0, 0, LoadingContainer.this.getWidth(), LoadingContainer.this.getHeight());
            }
        });
        this.setBackground(JBColor.BLACK);
    }

    public void loading() {
        processIcon.resume();
        loadingPanel.setVisible(true);
    }

    public void loaded() {
        processIcon.suspend();
        loadingPanel.setVisible(false);
    }

    public interface Loadable {

        default void loading() {
            Component component = this.getContent();
            Container container = component.getParent();
            if (container instanceof LoadingContainer) {
                ((LoadingContainer) container).loading();
            }
        }

        default void loaded() {
            Component component = this.getContent();
            Container container = component.getParent();
            if (container instanceof LoadingContainer) {
                ((LoadingContainer) container).loaded();
            }
        }

        Component getContent();

    }

}
